package org.nvframe.manager;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.nvframe.entity.Entity;

/**
 * 
 * @author Nik Van Looy
 */
public class EntityManager {
	
	private static EntityManager _instance = new EntityManager();
	private static int nextId;
	
	public static EntityManager getInstance() {
		return _instance;
	}
	
	private EntityManager() {
		entities = new HashMap<Integer,Entity> ();
		nextId = 0;
	}
	
	private Map<Integer, Entity> entities;

	/**
	 * Add an Entity to the manager for later reference
	 * 
	 * @param entity The entity to add
	 */
	public void addEntity(Entity entity) {
		int instanceId = getNextId();
		entity.setInstanceId(instanceId);
		entities.put(instanceId, entity);
	}
	
	/**
	 * Get a collection of alle Entities in the Manager instance
	 * 
	 * @return The entity collection
	 */
	public Collection<Entity> getEntities() {
		return entities.values();
	}
	
	/**
	 * Get an Entity reference from a specified id
	 * 
	 * @param entityId The Entity's id
	 * @return The Entityy
	 */
	public Entity getEntity(String entityId) {
		
		for(Entity entity : entities.values()) {
			if(entity.getId().equals(entityId))
				return entity;
		}
		
		return null;
	}
	
	/**
	 * Count instances of an entitiy with a specified id
	 * 
	 * @param entityId
	 * @param active true counts only active, false otherwise
	 * @return int instance count
	 */
	public int getEntityCount(String entityId, boolean active) {
		int count = 0;
		
		for(Entity entity : entities.values()) {
			if(entity.getId().equals(entityId) && entity.isEnabled() == active)
				count++;
		}
		
		return count;
	}
	
	/**
	 * Print all Entities held by the Manager
	 */
	public void printEntities() {
		int count = 0;

		for(Entity entity : entities.values()) {
			System.out.println("entity no."+ ++count + ": " + entity.getId());
		}
	}

	/**
	 * Remove an Entity from the Manager
	 * this method also calles the removed method from the Entity instance
	 * 
	 * @param id The Entity id
	 */
	public void removeEntity(String id) {
		// TODO implement EntityManager.removeEntity
	}

	/**
	 * Get the next Entity instance id
	 * 
	 * @return The next Entity-instance id
	 */
	private int getNextId() {
		return ++nextId;
	}

}
